package com.csx.springcloud.loadbalancer.scl.toSwitch;

import com.csx.springcloud.loadbalancer.scl.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import reactor.core.publisher.Mono;

/**
 * 该类主要是 实现根据用户的配置动态切换 负载均衡器
 * @author csx
 * @data 2023年7月22日11:19:47
 */
public class CsxDynamicLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private final Logger logger = LoggerFactory.getLogger(CsxDynamicLoadBalancer.class);

    private static final String DEFAULT_LOAD_STRATEGY = Constants.ROUND_ROBIN;

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ReactorServiceInstanceLoadBalancer loadBalancerClient = getLoadBalancer();
        return loadBalancerClient.choose(request);
    }

    @Override
    public Mono<Response<ServiceInstance>> choose() {
        ReactorServiceInstanceLoadBalancer loadBalancer = getLoadBalancer();
        return loadBalancer.choose();
    }

    private ReactorServiceInstanceLoadBalancer getLoadBalancer() {

        ReactorServiceInstanceLoadBalancer targetLoadBalancer = null;

        // TODO 这里只需要设计一种数据结构用于存储 从配置中心中获取 的 负载均衡器配置, 根据配置从 负载均衡器工厂中获取 相应的负载均衡器
        targetLoadBalancer = CsxLoadBalancerFactory.createLoadBalancer(DEFAULT_LOAD_STRATEGY);

        if(logger.isDebugEnabled()) {
            logger.debug("The loadBalancer actually used by the dynamicLoadBalancer is {}", targetLoadBalancer);
        }

        return targetLoadBalancer;


    }
}

